import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { create } from "@/store/settingCountry/settingCountryAPI";
import {
  changeModal,
  getCountryAsync,
} from "@/store/settingCountry/settingCountrySlice";
import { Form, Input, Modal, Select } from "antd";
import { useEffect, useState, type ReactElement } from "react";
import { shallowEqual } from "react-redux";

export default function Create(): ReactElement<typeof Modal, "div"> {
  const [loading, setLoading] = useState<boolean>(false);
  const { modal, params } = useAppSelector(
    (state) => state.settingCountry,
    shallowEqual
  );
  const {
    config: {
      data: {
        data: { user_channel_list = [] } = {},
      } = {},
    } = {},
  } = useAppSelector((state) => state.app, shallowEqual);
  const dispatch = useAppDispatch();
  const [form] = Form.useForm();

  const handleClose = () => {
    dispatch(changeModal({ open: false }));
    form.resetFields();
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      create({
        ...values,
        opt_type: 1
      })
        .then(() => {
          handleClose();
          dispatch(getCountryAsync({ ...params }));
        })
        .finally(() => {
          setLoading(false);
        });
    } catch (err) {
      console.log("校验不通过");
    }
  };

  useEffect(() => {
    if (modal.open && modal.type === "update") {
      form.setFieldsValue(modal.record);
    }
  }, [modal]);

  return (
    <Modal
      open={modal.open}
      title={modal.type === "create" ? "创建" : "编辑"}
      onCancel={handleClose}
      onOk={handleOk}
      confirmLoading={loading}
    >
      <Form form={form}>
        <Form.Item
          name="channel"
          rules={[{ required: true, message: "必填" }]}
          label="渠道"
        >
          <Select options={user_channel_list} />
        </Form.Item>
        <Form.Item
          name="country"
          rules={[{ required: true, message: "必填" }]}
          label="地区"
        >
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
}
